<?php declare(strict_types=1);

namespace app\admin\controller;

use app\admin\Diluma;
use app\admin\model\Admin as AdminModel;
use think\facade\Log;
use think\facade\View;
use app\admin\service\RoleService;
use app\admin\validate\AdminValidate;
use app\admin\service\MenuService;

class Admin extends Diluma
{

    /**
     * 首页
     * @return string
     */
    public function index()
    {
        $roleService = new RoleService();
        $roleItems = $roleService->getRoleList(PAGE_SIZE);
        View::assign('role_items', $roleItems);
        return View::fetch();
    }

    /**
     * 管理员列表
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function getList()
    {
        $roleId = $this->request->param('role_id');
        $pageSize = (int)$this->request->param('page_size', 10);

        $model = new AdminModel();
        $items = $model->alias('u')
            ->field(['u.id','u.role_id','u.username','u.nickname','u.phone','u.avatar','u.update_time','u.login_time','r.name'])
            ->leftJoin('admin_role r', 'u.role_id = r.id')
            ->where(function ($query) use ($roleId){
                if($roleId){
                    $query->where('u.role_id', $roleId);
                }
            })
            ->order(['u.id'=>'asc'])->paginate($pageSize);
        return json(['code'=>0, 'msg'=>'success', 'count'=>$items->total(), 'data'=>$items->items()]);
    }

    /**
     * 新增管理员
     * @return \think\response\Json
     */
    public function insert()
    {
        $model = new AdminModel();
        if($this->request->isPost()) {
            $post = $this->request->post();
            // 验证参数
            validate(AdminValidate::class)->scene('insert')->checkData($post['field']);
            try {
                if (isset($post['field']['password'])) {
                    $post['field']['password'] = md5($post['field']['password']);
                }
                $model->save($post['field']);
                return json(['code'=>0, 'msg'=>'添加成功']);
            } catch (\Exception $e) {
                $error = $e->getMessage();
                Log::error('insert admin user error:' .$error);
                return json(['code'=>1, 'msg'=>"添加失败：" .$error]);
            }
        } else {
            $roleService = new RoleService();
            $roleItems = $roleService->getRoleList(PAGE_SIZE);
            View::assign('role_items', $roleItems);
            return View::fetch();
        }
    }

    /**
     * 编辑管理员
     * @return \think\response\Json
     */
    public function edit()
    {
        $model = new AdminModel();
        if($this->request->isPost()) {
            $post = $this->request->post();
            validate(AdminValidate::class)->scene('edit')->checkData($post['field']);
            $item = $model->find($post['field']['id']);
            try {
                if (!empty($post['field']['password']) && !empty($post['field']['repassword'])) {
                    $post['field']['password'] = md5($post['field']['password']);
                    $post['password'] = md5($post['password']);
                    $post['repassword'] = md5($post['repassword']);
                    if ($post['field']['password'] == $item->password) {
                        return json(['code'=>1, 'msg'=>'新密码与原密码一致，无需修改']);
                    }
                    if($post['field']['password'] !== $post['field']['repassword']){
                        return json(['code'=>1, 'msg'=>'两次密码不一致']);
                    }
                } else {
                    unset($post['field']['password']);
                    unset($post['field']['repassword']);
                }
                $item->save($post['field']);
                return json(['code'=>0, 'msg'=>'编辑成功']);
            } catch (\Exception $e) {
                $error = $e->getMessage();
                Log::error('edit admin user error:' .$error);
                return json(['code'=>1, 'msg'=>"修改失败：" .$error]);
            }
        } else {
            $userId = $this->request->param('id');
            $item = $model->find($userId);
            $roleService = new RoleService();
            $roleItems = $roleService->getRoleList(PAGE_SIZE);
            View::assign('role_items', $roleItems);
            View::assign('item', $item);
            return View::fetch();
        }
    }

    /**
     * 权限预览
     * @return \think\response\Json
     */
    public function view()
    {
        $roleId = $this->request->param('role_id', 0, 'intval');
        View::assign('role_id', $roleId);
        return View::fetch();
    }

    /**
     * 管理员权限预览
     * @return \think\response\Json
     */
    public function getUserMenuList()
    {
        $service = new MenuService();
        $roleId = $this->request->param('role_id', 0, 'intval');
        $menuItems = $service->getUserMenuList($roleId);
        return json(['code'=>0, 'data'=>$menuItems]);
    }

    /**
     * 管理员删除
     * @return \think\response\Json|void
     */
    public function delete()
    {
        if($this->request->isAjax()) {
            $id = $this->request->param('id');
            if ($id == 1) {
                return json(['code'=>1, 'msg'=>'超级管理员不能删除']);
            }
            if($id == session('{ADMIN_LOGIN_INFO}')['admin_id']) {
                return json(['code'=>1, 'msg'=>'不能删除自己']);
            }
            $model = new AdminModel();
            try {
                $model::destroy($id);
                // 清除该用户的 session 会话信息
                return json(['code'=>0, 'msg'=>'删除成功']);
            } catch (\Exception $e) {
                Log::error("delete admin user error:". json_encode($e->getMessage()));
                return json(['code'=>1, 'msg'=>'删除失败：' .$e->getMessage()]);
            }
        }
    }

    /**
     * 修改资料
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function profile()
    {
        $adminInfo = \session('{ADMIN_LOGIN_INFO}');
        $id = $adminInfo['admin_id'];
        $model = new AdminModel();
        $item = $model->find($id);
        if($this->request->isPost()) {
            $post = $this->request->post();
            $field = $post['field'];
            if(!empty($field['password']) && !empty($field['repassword'])){
                $field['password'] = md5($field['password']);
                $field['repassword'] = md5($field['repassword']);
                if ($field['password'] == $item->password) {
                    return json(['code'=>1, 'msg'=>'新密码与原密码一致，无需修改']);
                }
                if($field['password'] !== $field['repassword']){
                    return json(['code'=>1, 'msg'=>'两次密码不一致']);
                }
            } else {
                unset($field['password']);
                unset($field['repassword']);
            }
            try {
                $item->save($field);
                return json(['code'=>0, 'msg'=>'修改成功']);
            } catch (\Exception $e) {
                Log::error('edit personal error:'. json_encode($e->getCode()));
                return json(['code'=>1, 'msg'=>'修改失败：'. json_encdoe($e->getCode())]);
            }
        } else {
            View::assign('item', $item);
            return View::fetch();
        }
    }
}